import {messages} from "share/common";
import React, { } from 'react';
import { connect } from 'react-redux'
import config from 'config'
import {Modal, Button, Tabs, Upload, Icon, message, Table, Alert} from 'antd'
const TabPane = Tabs.TabPane;
import httpFetch from 'share/httpFetch'
import IndirectUpload from './indirect-upload';
import 'styles/financial-management/check-center/check-center-impoter.scss'
//数据导入组件
class CheckCenterImporter extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isUpload: false,
      visible: false,
      isFinish: false,// 上传是否完成
      fileList: [],
      uploading: false,
      tabKey: 'UPDATE',
      result: {},
      transactionID: null,
      errorColumns:[],
      errorData: [],
      descTextOfDownload:[
        `1.${messages('financial-management.key90'/*点击上方按钮*/)}`,
        `2.${messages('financial-management.key91'/*严格按照导入模板整理数据，检查必输事项是否缺少数据*/)}`,
        `3.${messages('financial-management.key92'/*保存文件*/)}`
      ],
      descTextOfUpload:[
        `1.${messages('financial-management.key94'/*点击【选择文件】按钮*/)}`,
        `2.${messages('financial-management.key95'/*选择你刚更新过的Excel文件，并点击确定*/)}`,
        `3.${messages('financial-management.key96'/*点击【导入】按钮*/)}`
      ],
    };
  }

  componentWillReceiveProps(nextProps) {
    this.setState({ visible: nextProps.visible, tabKey: 'UPDATE' })
  }

  componentWillMount(){
    const { isReplace, descUpload, descDownload, errorColumns } = this.props;
    let { descTextOfUpload, descTextOfDownload } = this.state;
    if(isReplace){
      if(descDownload){
        descTextOfDownload = descDownload;
      }
      if(descUpload){
        descTextOfUpload = descUpload;
      }
    }else{
      if(descDownload){
        descTextOfDownload = descTextOfDownload.concat(descDownload);
      }
      if(descUpload){
        descTextOfUpload = descTextOfUpload.concat(descUpload)
      }
    }
    let columns =  [
      {title: messages('financial-management.key79'/*行号*/), dataIndex: 'rowNum', width: '13%'},
      {title: messages('financial-management.key42'/*订单号*/), dataIndex: 'recordId', width: '25%'},
      {title: messages('financial-management.key80'/*错误信息*/), dataIndex: 'error'}
    ]
    if(errorColumns){
      this.setState({descTextOfUpload, descTextOfDownload, errorColumns:errorColumns})
    }else{
      this.setState({descTextOfUpload, descTextOfDownload,errorColumns:columns})
    }
  }

  handleOk = () => {
    const { tabKey } = this.state;
    //在导入tab下为上传
    if(tabKey === 'UPDATE'){
      this.setState({isUpload: true,tabKey: 'SUCCESS',})
    } else {
      this.props.onOk('close');
      this.setState({
        visible: false,
        isFinish: false,
        tabKey: 'UPDATE'
      })
    }
  };

  finishUpload = (res) => {
    const { resultCallBack } = this.props;
    if(res.data){
      this.setState({
        isFinish: true,
        isUpload: false,// 下面那行真不是我写的，不明白为什么会这么。。。。。，所以咱也不敢动。
        transactionID: res.data.transactionID || res.data.transactionOID || res.data.transactionUUID || res.data
      },() => {
        this.setState({
          fileList: [],
          uploading:false,
          result:resultCallBack ? resultCallBack(res,'result') : res.data.body,
          errorData:resultCallBack ? resultCallBack(res,'errorData') : res.data.body.errorList
        })
      });
    }else{
      message.error(JSON.stringify(res));
    }
  }

  setFileList = (fileList) => {
    this.setState({fileList: fileList});
  }

  onCancel = () => {
    this.setState({visible: false, uploading: false, isFinish: false});
    if (this.state.uploading && this.state.transactionID) {
      httpFetch.delete(`${config.budgetUrl}/api/budget/batch/transaction/logs/${this.state.transactionID}`)
    }
  };

  //下载导入模板
  downloadTemplate = () => {
    let hide = message.loading(messages('financial-management.key82'/*正在生成文件..*/));
    const { templateMethod, templateCallBack, templateParams } = this.props;
    let method = templateMethod || 'get';
    httpFetch[method](this.props.templateUrl, templateParams || {}).then(res => {
      if(templateCallBack){
        templateCallBack(res);
      }else if(res.data.exportFileRecord.tempUrl){
        window.open(res.data.exportFileRecord.tempUrl);
      }
      hide();
    }).catch(() => {
      message.error(messages('financial-management.key83'/*下载失败，请重试*/));
      hide();
    })
  };

  // 下载错误信息
  onDownloadError = () => {
    httpFetch.post(this.props.downloadErrorUrl,this.state.result).then(res => {
      window.open(res.data.path);
    }).catch(() => {
      message.error(messages('financial-management.key83'/*下载失败，请重试*/));
      hide();
    })
  }

  //只能上传一个文件
  handleChange = (info) => {
    let fileList = info.fileList;
    fileList = fileList.slice(-1);
    this.setState({ fileList })
  };

  setModalFooter = () => {
    const { tabKey, isFinish } = this.state;
    return (
      <div>
        <Button onClick={this.onCancel}>{messages('common.cancel')/*取消*/}</Button>
        {tabKey === 'UPDATE' && <Button type='primary' disabled={!isFinish} onClick={this.handleOk}>{messages('financial-management.key85'/*导 入*/)}</Button>}
        {!(tabKey === 'UPDATE') && <Button type='primary' onClick={this.handleOk}>{messages('financial-management.key86'/*完 成*/)}</Button>}
      </div>
    )
  }

  render() {
    const { title, uploadUrl, isDownloadError, params } = this.props;
    const { isUpload, visible, uploading, tabKey, result, errorColumns, errorData, descTextOfDownload, descTextOfUpload } = this.state;

    return (
      <Modal className="importer"
             visible={visible}
             onCancel={this.onCancel}
             afterClose={this.props.afterClose}
             title={title}
             footer={this.setModalFooter()}
             confirmLoading={uploading}
      >
        <Tabs defaultActiveKey="UPDATE" activeKey={tabKey} onChange={(key) => {this.setState({ tabKey: key })}}>
          <TabPane tab={messages('financial-management.key87'/*上传文件*/)} key="UPDATE" disabled={tabKey === 'SUCCESS'}>
            {
              false && <div>
                <h3>{messages('financial-management.key88'/*创建电子表格*/)}</h3>
                <Button type="primary" onClick={this.downloadTemplate}>
                  {messages('financial-management.key89'/*下载Excel电子表格*/)}
                </Button>
                {
                  descTextOfDownload.map((item,index) => {
                    return (
                      <div style={{margin:'2px 0'}} key={index}>{item}<br/></div>
                    )
                  })
                }
              </div>
            }
            <h3>{messages('financial-management.key93'/*上传电子表格*/)}</h3>
            {
              descTextOfUpload.map((item,index) => {
                return (
                  <div style={{margin:'2px 0'}} key={index}>{item}<br/></div>
                )
              })
            }
            {
              visible && <IndirectUpload
                returnFileList={this.setFileList}
                uploadUrl={uploadUrl}
                params={params}
                finishUpload={this.finishUpload}
              />
            }
          </TabPane>
          <TabPane tab={messages('financial-management.key98'/*导入结果*/)} key="SUCCESS" disabled={tabKey === 'UPDATE'}>
            {!result.fail && result.success ? (
              <Alert
                message={messages('financial-management.key544',{arg1: result.success+''}/*导入成功：{arg1}条*/)}
                type="success"
                showIcon
              />
            ) : (
              <span>{messages('financial-management.key544',{arg1: result.success+''}/*导入成功：{arg1}条*/)}</span>
            )}
            {!!result.fail && (
              <Alert
                message={`${messages('financial-management.key545',{arg1: result.fail+''}/*导入失败：{arg1}条*/)}${ (result.fail > 4 && isDownloadError) ? ','+ messages('financial-management.key816')/*请下载错误信息查看详情*/ : ''}`}
                type="error"
                style={{marginTop: 8}}
                showIcon
              />)}
            {result.fail > 4 ?
              <div style={{marginTop:10, marginBottom: 5}}>
                { isDownloadError && <a onClick={this.onDownloadError}>{messages('financial-management.key802')/*下载错误信息*/}</a>}
                ({messages('financial-management.key99'/*请修改相应数据后，重新导入*/)})
              </div> : ''}
            {result.fail ? (
              <div>
                <Table rowKey={record => record.rowNum}
                       columns={errorColumns}
                       dataSource={errorData}
                       pagination={false}
                       scroll={{x: false, y: 170}}
                       bordered
                       size="small"/>
              </div>
            ) : ''}
          </TabPane>
        </Tabs>
      </Modal>
    );
  }
}

CheckCenterImporter.propTypes = {
  visible: React.PropTypes.bool,           //导入弹框是否可见
  templateUrl: React.PropTypes.string,    //模版下载接口
  uploadUrl: React.PropTypes.string,     //上传接口
  errorUrl: React.PropTypes.string,    //错误信息下载接口，不需要写transactionID变量
  title: React.PropTypes.string,      //标题
  fileName: React.PropTypes.string,  //下载文件名
  onOk: React.PropTypes.func,       //导入成功回调
  afterClose: React.PropTypes.func,//关闭后的回调
  descDownload: React.PropTypes.array,//下载模板描述
  descUpload: React.PropTypes.array,//上传模板描述
  isReplace: React.PropTypes.bool,//是否替换原来描述
};

CheckCenterImporter.defaultProps = {
  title: '导入',
  fileName: '导入文件',
  isReplace: false,
  params: {},
  onOk: () => {},
  afterClose: () => {},
};

function mapStateToProps() {
  return {}
}

export default connect(mapStateToProps)(CheckCenterImporter);
